package com.kerwin.utils;

import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Objects;

/*用来获取request 和 response 的*/
public class ServletUtil {

    public static ServletRequestAttributes getRequestAttributes(){
        /*这是个接口，把它转成实现类*/
                                             /*这是从threadLocal把 ServletRequestAttributes  拿出来*/
//      RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
        return requestAttributes;
    }

    public static HttpServletRequest getRequest(){
        return getRequestAttributes().getRequest();
    }

    public static HttpServletResponse getResponse(){
        return getRequestAttributes().getResponse();
    }



    /*传入 PAGE_NUM="pageNum" 这种 前端请求参数  获得页数 或 页容量*/
    public static String getParameter(String key,String defaultValue){
        String parameter = getRequest().getParameter(key);
        if(Objects.isNull(parameter)){
            return defaultValue;
        }
        return parameter;
    }

    public static Integer getParameter(String key,Integer defaultValue){
        //String parameter = getRequest().getParameter(key);
        if(Objects.isNull(key)){
            return defaultValue;
        }
        return Integer.parseInt(key);
    }


}
